/* eslint-disable react/jsx-pascal-case */


import { History } from "history";
import React from "react"
import classnames from 'classnames';
import Genie from 'component/Genie';
import './index.less';

export interface MipProps {

    /** 应用标识 */
    id: string;

    /** 样式名 */
    className?: string;

    /** 样式 */
    style?: React.CSSProperties;

    /** 传递给app的参数 */
    appProps?: any;

    /** 模块名称 */
    moduleName?: string;

    /** 加载器 */
    spin?: React.ReactChild;

    /** 路由 */
    history?: History;

    /** 孩子 */
    children?: React.ReactNode
}

export default function Mic(props: MipProps) {

    const appContainer = React.useRef<HTMLDivElement>(null);

    const App = React.useRef<React.ComponentType<any>>()

    const [version, setVersion] = React.useState(0);

    React.useEffect(() => {
        const genie = new Genie({
            id: props.id,
            appContainer: appContainer.current,
        });

        genie.init().then(() => {
            App.current = genie.getModule(props.moduleName);
            setVersion(e => e + 1);
        })

        return () => {
            genie.distinct();
        }
    }, [props.id, props.moduleName])

    return (
        <div
            key={version}
            app-id={props.id}
            ref={appContainer}
            style={props.style}
            className={classnames(['mic-app', props.className])}
        >
            {
                App.current
                    ? <App.current {...props.appProps} history={props.history} >{props.children}</App.current>
                    : props.spin
            }
        </div>
    )
}